<template>
	<div class="sql-editor-box">
		<div class="sql-editor-toolbar">
			<el-row :gutter="10">
				<el-col :span="1.5">
					<el-button icon="el-icon-videoPlay" circle size="small" :disabled="!connectionId"
						@click="sqlQueryHandle" />
				</el-col>
				<el-col :span="1.5">
					<el-button icon="el-icon-magicStick" circle size="small" :disabled="!connectionId" />
				</el-col>
				<el-col :span="1.5">
					<el-button icon="el-icon-folderAdd" circle size="small" />
				</el-col>
				<el-col :span="1.5">
					<el-button icon="el-icon-message" circle size="small" />
				</el-col>
			</el-row>
		</div>

		<div class="sql-editor-toolbar">
			<el-row :gutter="10">
				<el-col :span="1.5">
					<el-select v-model="connectionId" class="m-2" placeholder="选择连接" size="small" clearable
						@change="((val) => { getCatalogList(val) })">
						<el-option v-for="item in connList" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-col>
				<el-col :span="1.5">
					<el-select v-model="catalogName" class="m-2" placeholder="选择数据库" size="small" clearable>
						<el-option v-for="item in catalogList" :key="item.name" :label="item.name" :value="item.name" />
					</el-select>
				</el-col>

			</el-row>
		</div>

		<div class="magic-monaco-editor-wrapper">
			<monaco-editor ref="sqlEditor" v-model:modelValue="sql" :language="language"
				v-model:selectedCatalog="catalogName" :hight-change="hightChange" read-only="false"
				@editor-mounted="editorMounted" :on-input-field="onInputField" v-model:dbs="dbs" />

			<!-- <monaco-sqlpad v-model="sql" :on-input-field="onInputField" :dbs="dbs" :width="500" :height="500" /> -->
		</div>



		<div style="margin-bottom: 10px;">运行结果</div>
		<el-tabs v-model="resultTabs.activeTab" type="card">
			<el-tab-pane label="消息" name="message" :closable="false">
				<el-scrollbar>
					<div class="result-box">

						<div v-for="item in executeResult" class="result-message">
							<div>{{ item.sql }}</div>
							<div :style="{ color: item.success ? '' : 'red' }">>>{{ item.message }}</div>
							<div>>>查询时间：{{ item.time }}秒</div>
						</div>

					</div>
				</el-scrollbar>
			</el-tab-pane>
			<el-tab-pane v-for="(item, index) in executeResultTabs(executeResult)" :label="`结果${index}`" :key="index"
				closable>

				<el-table :data="item.rows" style="width: 100%" max-height="193">
					<el-table-column :prop="columns.field" :label="columns.field" v-for="columns in item.columns ">
					</el-table-column>
				</el-table>

				<div style="position: fixed; /*or前面的是absolute就可以用*/  
		       bottom: 0px;  ">
					lkajsdlf
				</div>


			</el-tab-pane>
		</el-tabs>


		<!-- <div style="position: fixed; /*or前面的是absolute就可以用*/  
			       bottom: 0px;  ">
			<dbant-navbar direction="horizontal" ref="navbar" class="magic-navbar">
				<dbant-navbar-item key="1" title="底部测试" icon="query">
					<magic-resizer direction="y" :max="700" :min="150" :value="250">
						<div>asdjflkajsdf</div>
					</magic-resizer>
				</dbant-navbar-item>
			</dbant-navbar>
		</div> -->
	</div>
</template>
<script>
import MonacoEditor from '../../../components/monacoEditor.vue'
// import MonacoEditor from "../../../plugins/MonacoEditor";
import { ref } from "vue"
// import MonacoSqlpad from 'monaco-sqlpad'
import MagicResizer from "./magic-resizer.vue"
import Home from "../../Home.vue"
import test from "./test.vue"
export default {
	components: {
		MonacoEditor,

		Home,
		test,
		MagicResizer

	},
	props: {
		connId: Number,
		catalog: String
	},
	data() {
		return {
			connectionId: ref(this.connId),
			catalogName: ref(this.catalog),
			sql: "",
			language: "sql",
			hightChange: "false",
			connList: [],
			catalogList: [],
			dbs: ref([]),
			executeState: ref(false),
			activeBottomTab: '',
			executeResult: ref([]),
			resultTabs: {
				activeTab: 'message'
			}
		}
	},
	computed: {
		iconStyleObject: () => {
			return (node) => {
				if (node.data.type === "CONN") {
					let color = node.childrenLoaded ? "#165EFF" : "#8a8a8a";
					return `color:` + color + `;margin-right:2px`;
				}
				return `color:#165EFF;margin-right:2px`;
			};
		},


	},
	async mounted() {
		this.initData();
		// 初始化数据库及表信息用于编辑器提示数据库和表
		//	this.dbs = await this.getDbList()
		console.log(this.dbs)
	},
	methods: {
		executeResultTabs: (executeResult) => {
			return executeResult.filter(item => item.success)
		},
		initData() {
			this.$API.connection.getTree().then((res) => {
				this.connList = res.data;
			});
		},
		getCatalogList(connId) {
			const connItem = this.connList.find(value => value.id == connId);
			console.log(connItem);
			this.catalogList = [];
			const params = { connId: connItem.properties.connId };
			//请求数据库信息
			this.$API.metadata
				.executeFunction({
					type: connItem.type,
					pluginId: connItem.properties.pluginId,
					params: params,
				})
				.then((res) => {
					this.catalogList = res.data;
				})
			//请求该连接得所有元数据信息
			this.$API.metadata
				.executeFunction({
					type: 'allMetadataEditorKey',
					pluginId: connItem.properties.pluginId,
					params: params,
				})
				.then((res) => {
					this.dbs = res.data
				})

		},
		editorMounted(editor) {
			console.log('editor实例加载完成', editor)

		},
		sqlQueryHandle() {

			this.executeResult = [];
			const selectSql = this.$refs.sqlEditor.getSelectionVal();

			const executeParams = { script: selectSql ? selectSql : this.sql };
			const params = { connId: this.connectionId, catalog: this.catalogName, executeParams: executeParams };
			//请求后台获取子节点数据
			this.$API.sqlDatabase
				.executeSqlScript(params)
				.then((res) => {
					this.executeResult = res.data;
				})
		},

		async onInputField(dbName, tableName) {
			const fields = await this.getTableCloumn(dbName, tableName)
			return fields
		},
		/**
		 * 模拟异步获取数据库名&&表名
		 */
		getDbList() {
			return new Promise((resolve, reject) => {
				resolve([
					{
						dbName: 'db_bar',
						tables: [
							{
								tblName: 'user',
								tableColumns: [
									{
										columnName: 'username'
									},
									{
										columnName: 'username1'
									},
									{
										columnName: 'username2'
									},
								]
							},
							{
								tblName: 'log',
								tableColumns: [{
									columnName: 'logColums'
								},
								{
									columnName: 'logColums1'
								},]
							},
							{
								tblName: 'goods',
								tableColumns: [,
									{
										columnName: 'goods1'
									}]
							}
						]
					},
					{
						dbName: 'db_foo',
						tables: [
							{
								tblName: 'price',
								tableColumns: []
							},
							{
								tblName: 'time',
								tableColumns: []
							},
							{
								tblName: 'updata_user',
								tableColumns: []
							}
						]
					},
					{
						dbName: 'select',
						tables: [
							{
								tblName: 'price',
								tableColumns: []
							},
							{
								tblName: 'time',
								tableColumns: []
							},
							{
								tblName: 'updata_user',
								tableColumns: []
							}
						]
					}
				])
			})
		},
		/**
		 * 模拟异步获取表字段
		 */
		getTableCloumn(dbName, tableName) {
			const connItem = this.connList.find(value => value.id == this.connectionId);
			const params = { catalog: dbName, tableName: tableName, connId: this.connectionId };
			console.log(params)
			return new Promise((resolve, reject) => {
				//请求该连接得所有元数据信息
				this.$API.metadata
					.executeFunction({
						type: 'columnsEditorKey',
						pluginId: connItem.properties.pluginId,
						params: params,
					})
					.then((res) => {
						resolve(res.data)
					})
			})
		}
	}
};
</script>
<style lang="scss" scoped>
.sql-editor-toolbar {
	width: 100%;
	background: #ffff;
	padding: 5px 10px;
}

// .el-main {
// 	padding: 0px;
// }

:deep(.el-header) {
	padding: 0px;
	height: 35px;
}

.sql-editor-wrap {
	width: 100%;
	// min-height: 700px;
	height: 100%;
	overflow: hidden;
	text-align: left;
}

:deep(.margin-view-overlays) {
	background: #f6f8f9;
}

:deep(.el-main) {
	padding: 0px 0px 0px 0px;
}

:deep(.el-footer) {
	padding: 10px 10px;
	height: 100%;
}

.result-message {
	margin-bottom: 10px;

}

:deep(.el-tabs) {
	--el-tabs-header-height: 30px;
}

.result-box {
	max-height: 240px
}

.magic-toolbar .magic-navbar {
	flex-direction: column-reverse;
}

.magic-toolbar-header {
	height: 26px;
	line-height: 26px;
	border-bottom: 1px solid var(--main-border-color);
	border-top: 1px solid var(--main-border-color);
	background-color: var(--main-background-color);
}

.magic-toolbar-header+div {
	z-index: 99999;
}

.magic-toolbar-header label {
	display: inline-block;
	padding-left: 10px;
}

.magic-toolbar .magic-resizer-y {
	flex-direction: column;
}

.magic-toolbar-header-buttons {
	float: right;
	margin-right: 5px;
	vertical-align: middle;
	display: flex;
	align-items: center;
	height: 26px;
}

.magic-toolbar-header-buttons .magic-icon {
	display: inline-block;
	cursor: pointer;
	padding: 0 2px;
	height: 18px;
	line-height: 18px;
	border-radius: 3px;
	z-index: 99999;
}

.magic-toolbar-header-buttons .magic-icon:hover {
	background-color: var(--main-hover-icon-background-color);
}

.magic-toolbar .magic-navbar :deep(.magic-navbar-body) {
	background-color: var(--main-background-color);
}


.magic-monaco-editor-wrapper {

	flex: 1 1 auto;
	height: calc(100vh - 320px);
}
</style>
